package com.ysd.lis.service.lab.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.lab.LabFinanceSalesSettle;
import com.ysd.lis.entity.lab.LabFinanceSalesSettleDetall;
import com.ysd.lis.entity.lab.LabFinanceSettle;
import com.ysd.lis.mapper.lab.LabFinanceSalesSettleMapper;
import com.ysd.lis.mapper.lab.LabFinanceSettleMapper;
import com.ysd.lis.request.lab.SalesSettleDto;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.lab.LabFinanceSalesSettleDetallService;
import com.ysd.lis.service.lab.LabFinanceSalesSettleService;
import com.ysd.lis.service.lab.LabFinanceSettleService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售财务结算 服务实现类
 * </p>
 *
 * @author WH
 * @since 2024-11-06
 */
@Service
public class LabFinanceSalesSettleServiceImpl extends ServiceImpl<LabFinanceSalesSettleMapper, LabFinanceSalesSettle> implements LabFinanceSalesSettleService {

    @Autowired
    LabFinanceSalesSettleMapper labFinanceSalesSettleMapper;
    @Autowired
    LabFinanceSalesSettleDetallService labFinanceSalesSettleDetallService;
    @Autowired
    LabFinanceSettleMapper labFinanceSettleMapper;

    @Autowired
    LabFinanceSettleService labFinanceSettleService;

    @Autowired
    SysRuleSetService sysRuleSetService;


    @Override
    public Result findFinanceSalesSettleList(SalesSettleDto param) {
        MPJLambdaWrapper<LabFinanceSalesSettle> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabFinanceSalesSettle.class);
        if (ToolsUtils.isNotEmpty(param.getSalesmanCode())) {
            queryWrapper.eq(LabFinanceSalesSettle::getSalesmanCode, param.getSalesmanCode());
        }

        String settleDateBegin = param.getSettleDateBegin();
        if (ToolsUtils.isNotEmpty(settleDateBegin)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(settleDateBegin);
                Timestamp timestampBeg = new Timestamp(date.getTime());
                queryWrapper.ge(LabFinanceSalesSettle::getSettleDate, timestampBeg);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String settleDateEnd = param.getSettleDateEnd();
        if (ToolsUtils.isNotEmpty(settleDateEnd)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(settleDateEnd);
                Timestamp timestampEnd = new Timestamp(date.getTime());
                queryWrapper.le(LabFinanceSalesSettle::getSettleDate, timestampEnd);
            } catch (ParseException e) {
                e.printStackTrace();            }
        }

        if (StringUtils.isNotBlank(param.getSearchValue())) {
            queryWrapper.and(wrapper -> wrapper.like(LabFinanceSalesSettle::getSalesSettleNo, param.getSearchValue())
                    .or().like(LabFinanceSalesSettle::getSalesmanCode, param.getSearchValue())
                    .or().like(LabFinanceSalesSettle::getSalesmanName, param.getSearchValue()));
        }
        queryWrapper.eq(LabFinanceSalesSettle::getDelFlag, 0);
        List<LabFinanceSalesSettle> financeSettleList = labFinanceSalesSettleMapper.selectList(queryWrapper);
        return Result.succ(1, "查询成功", financeSettleList);
    }

    @Override
    public Result findFinanceSettlesBySales(SalesSettleDto param) {
        //先根据ID查询明细
        MPJLambdaWrapper<LabFinanceSalesSettleDetall> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabFinanceSalesSettleDetall.class);
        queryWrapper.eq(LabFinanceSalesSettleDetall::getDelFlag, 0);
        queryWrapper.eq(LabFinanceSalesSettleDetall::getSalesSettleId, param.getSalesSettleId());
        List<LabFinanceSalesSettleDetall> settleReqList = labFinanceSalesSettleDetallService.list(queryWrapper);
        List<String> collect = settleReqList.stream().map(LabFinanceSalesSettleDetall::getSettleNo).distinct().collect(Collectors.toList());
        HashSet set = new HashSet();
        for(String reqNos : collect){
            String[] split = reqNos.split(",");
            for(String s : split){
                set.add(s);
            }
        }
        MPJLambdaWrapper<LabFinanceSettle> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabFinanceSettle.class);
        lambdaQueryWrapper.eq(LabFinanceSettle::getDelFlag, 0);
        if(ToolsUtils.isNotEmpty(param.getCompanyCode())){
            lambdaQueryWrapper.eq(LabFinanceSettle::getCompanyCode , param.getCompanyCode());
        }
        lambdaQueryWrapper.in(LabFinanceSettle::getSettleNo, set);
        List<LabFinanceSettle> list = labFinanceSettleMapper.selectList( lambdaQueryWrapper);

        return Result.succ(1, "查询成功", list);
    }

    @Override
    public Result batchDeleteSalesSettleList(SalesSettleDto dto) {
        List<LabFinanceSalesSettleDetall> financeSalesSettleDetallList = dto.getFinanceSalesSettleDetallList();
        List<String> ids = financeSalesSettleDetallList.stream().map(LabFinanceSalesSettleDetall::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if (b) {
            LambdaQueryWrapper<LabFinanceSalesSettleDetall> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabFinanceSalesSettleDetall::getDelFlag,0)
                    .in(LabFinanceSalesSettleDetall::getSalesSettleId,ids);
            List<LabFinanceSalesSettleDetall> list = labFinanceSalesSettleDetallService.list(queryWrapper);

            List<String> detallIds = list.stream().map(LabFinanceSalesSettleDetall::getId).collect(Collectors.toList());
            labFinanceSalesSettleDetallService.removeByIds(detallIds);
            //修改
            List<String> settleNos = list.stream().map(LabFinanceSalesSettleDetall::getSettleNo).collect(Collectors.toList());
            List<String> settleNolist = new ArrayList<>();
            for(String s : settleNos){
                String[] split = s.split(",");
                for(String ss : split){
                    settleNolist.add(ss);
                }
            }
            if(ToolsUtils.isNotEmpty(settleNolist)){
                LambdaUpdateWrapper<LabFinanceSettle> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(LabFinanceSettle::getSettleStatus, 5).in(LabFinanceSettle::getSettleNo, settleNolist);
                labFinanceSettleMapper.update(null,lambdaUpdateWrapper);
            }


            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result saveFinanceSalesSettle(LabFinanceSalesSettle labFinanceSalesSettle) {
        List<LabFinanceSalesSettleDetall> salesSettleDetalls = labFinanceSalesSettle.getSalesSettleDetalls();


        Integer totalSettleNum = salesSettleDetalls.stream().map(LabFinanceSalesSettleDetall::getSettleNum).reduce(0, Integer::sum);
        Double costs = salesSettleDetalls.stream().filter(x ->  Objects.nonNull(x.getCosts())).mapToDouble(LabFinanceSalesSettleDetall::getCosts).sum();
        Double realCosts = salesSettleDetalls.stream().filter(x ->  Objects.nonNull(x.getRealCosts())).mapToDouble(LabFinanceSalesSettleDetall::getRealCosts).sum();
        Double brokerageCosts = salesSettleDetalls.stream().filter(x ->  Objects.nonNull(x.getBrokerageCosts())).mapToDouble(LabFinanceSalesSettleDetall::getBrokerageCosts).sum();
        labFinanceSalesSettle.setSettleNum(totalSettleNum);
        labFinanceSalesSettle.setCosts(costs);
        labFinanceSalesSettle.setRealCosts(realCosts);
        labFinanceSalesSettle.setBrokerageCosts(brokerageCosts);
        //生成结算单号
        String financeNo = sysRuleSetService.createRuleCodeList("SalesNo", 1).get(0);
        labFinanceSalesSettle.setSalesSettleNo(financeNo);
        labFinanceSalesSettle.setSettleDate(new Timestamp(System.currentTimeMillis()));
        labFinanceSalesSettleMapper.insert(labFinanceSalesSettle);
        for (LabFinanceSalesSettleDetall salesSettleDetall : salesSettleDetalls) {
            salesSettleDetall.setSalesSettleId(labFinanceSalesSettle.getId());
            salesSettleDetall.setSalesSettleNo(financeNo);
        }
        labFinanceSalesSettleDetallService.saveBatch(salesSettleDetalls);
        //修改财务结算更改状态为15
        List<String> allSettleNos = salesSettleDetalls.stream().map(LabFinanceSalesSettleDetall::getSettleNo).flatMap(settleNo -> Arrays.stream(settleNo.split(","))).collect(Collectors.toList());
        labFinanceSettleService.update(new LambdaUpdateWrapper<LabFinanceSettle>().set(LabFinanceSettle::getSettleStatus, "15").in(LabFinanceSettle::getSettleNo, allSettleNos).eq(LabFinanceSettle::getDelFlag, 0));
        return Result.succ(1,"结算成功!",labFinanceSalesSettle);
    }
}
